package org.petstore.persistence.impl;

import org.petstore.domain.Sequence;

import org.petstore.persistence.SequenceDAO;
import org.petstore.persistence.util.JDBCUtils;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class SequenceDAOImpl implements SequenceDAO {
    private static final String GET_SEQUENCE = "SELECT name, nextid" +
            "    FROM SEQUENCE" +
            "    WHERE NAME = ?";
    private static final String UPDATE_SEQUENCE = "" +
            "    UPDATE SEQUENCE" +
            "    SET NEXTID = ?" +
            "    WHERE NAME = ?";
    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * description todo Sequence不清楚用法
     *
     * @param sequenceName:
     * @return Sequence
     * @author huangzhangyan
     * @date 2021/11/1 0:16
     */
    @Override
    public Sequence getSequenceByName(String sequenceName) {
        Sequence sequence;
        try {
            sequence = template.queryForObject(GET_SEQUENCE, new BeanPropertyRowMapper<>(Sequence.class), sequenceName);
            return sequence;
        } catch (DataAccessException e) {
            return null;
        }
    }

    /**
     * description todo Sequence不清楚用法
     *
     * @param sequence:
     * @author huangzhangyan
     * @date 2021/11/1 0:17
     */
    @Override
    public void updateSequence(Sequence sequence) {
        template.update(UPDATE_SEQUENCE, sequence.getNextId(), sequence.getName());
    }
}
